package com.sealer.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {
    /**
     * 将String格式的日期按照指定的日期格式转换成Date类型
     */
    public static Date parseDate(String dateString, String pattern) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        try {
            return simpleDateFormat.parse(dateString);
        } catch (ParseException e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }

    /**
     * 将Date格式的日期按照指定的日期格式转换成String类型
     */
    public static String parseString(Date dDate, String pattern) {
        return (new SimpleDateFormat(pattern)).format(dDate);
    }

    /**
     * {比较两个日期的大小 .如果date1在date2之后，返回true; date1在date2之前或相等，返回false}
     *
     * @param date1
     * @param date2
     * @return
     * @version 1.0
     * @since 1.0
     */
    public static boolean dateCompare(Date date1, Date date2) {
        return date1.compareTo(date2) > 0 ? true : false;
    }

    /**
     * 得到日期为当年的第几天，返回3位，不足3位左补0
     *
     * @param date
     * @return
     */
    public static String calculateDays(Date date) {
        int dateSum = 0;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(date);
        Integer year = Integer.valueOf(dateStr.substring(0, 4));
        Integer month = Integer.valueOf(dateStr.substring(5, 7));
        Integer day = Integer.valueOf(dateStr.substring(8, 10));
        for (int i = 1; i < month.intValue(); i++) {
            switch (i) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    dateSum += 31;
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    dateSum += 30;
                    break;
                case 2:
                    if (((year.intValue() % 4 == 0) & (year.intValue() % 100 != 0)) | (year.intValue() % 400 == 0))
                        dateSum += 29;
                    else
                        dateSum += 28;
            }
        }
        dateSum = dateSum + day.intValue();
        String str = String.valueOf(dateSum);
        while (str.length() < 3) {
            str = "0" + str;
        }

        return str;
    }

    /**
     * 计算当日和某天的天数
     *
     * @param beginDate
     * @return int
     */
    public static int diffDays(String beginDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date d1;
        try {
            d1 = sdf.parse(beginDate);
            return (int) ((new Date().getTime() - d1.getTime()) / (3600L * 1000 * 24));
        } catch (ParseException e) {

        }
        return 0;
    }

}
